package _tema6;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Iterator;
import java.util.Vector;


public class Servidor extends Thread {
	private PanelControlServidor pnl;
	private int port;
	private int cola;
	private ServerSocket ss;
	public boolean iniciado = true;
	private Vector<Socket> vs = new Vector<Socket>();
	
	
	
	public Servidor(PanelControlServidor pnl,int port, int cola){
		this.pnl = pnl;
		this.port = port;
		this.cola = cola;
	}

	public void run(){
		Socket s;
		try {
			this.ss = new ServerSocket(this.port,this.cola);
			this.pnl.cambiarEstadoServicio(true);
			this.iniciado = true;
			while (true){
				s = this.ss.accept();
				if (this.iniciado){
					this.vs.add(s);
					new ServidorThread(s,this.pnl).start();
				}
			}
		} catch (IOException e) {
			if (this.iniciado){
				this.pnl.cambiarEstadoServicio(false);
				this.pnl.mostrarMensajeComplementario("Se produjo un inconveniento.");
			}else{
				this.pnl.cambiarEstadoServicio(false);
			}
		}
	}

	public void shutdown(){
		try {
			this.iniciado = false;
			this.ss.close();
			Iterator i = this.vs.iterator();
			while (i.hasNext()){
				Socket s = (Socket) i.next();
				s.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			this.pnl.cambiarEstadoServicio(false);
			this.pnl.mostrarMensajeComplementario("Se produjo un inconveniente.");
		}
	}


}
